Page({
  data: {
    isAddress: true,
    isShowEmptyAddress: false,
    isShowAddress: false,
    emptyaddress:false,
    token: "",
    goodsList: [],
    amount: 0,
    ids: [],
    indexArr: [],
    address_id:"",
    //付款
    appid: "",
    timeStamp: "",
    nonce_str: "",
    package: "",
    signType: "MD5",
    paySign: "" ,
    address: ""
  },
  onPageScroll(e) {
    if (e.scrollTop >= 40 && !this.data.isAddress) {
      this.setData({
        isShowEmptyAddress: true
      })
    } else if (e.scrollTop < 40 && !this.data.isAddress) {
      this.setData({
        isShowEmptyAddress: false
      })
    }
    if (e.scrollTop >= 40 && this.data.isAddress) {
      this.setData({
        isShowAddress: true
      })
    } else if (e.scrollTop < 40 && this.data.isAddress) {
      this.setData({
        isShowAddress: false
      })
    }
  },
  onLoad(option) {
    console.log("我是从添加地址跳转过来的")
    // console.log(option)
    // console.log(option.selecAddress)
    //存进缓存中
    let { indexArr } = option
    //将选中商品的下表保存起来
    this.setData({
      indexArr: JSON.parse(indexArr)
    })
    this.getGoodsData()
  },
  onShow(){
    // 从添加地址跳转过来的只触发onshow方法
    // console.log("我是从添加地址跳转过来的")
    this.regAddress()
    
  },
  //初次加载获取选中商品的数据
  getGoodsData() {
    wx.getStorage({
      key: "token",
      success: (res) => {
        this.setData({
          token: res.data
        })
        wx.request({
          url: "http://api_devs.wanxikeji.cn/api/shoppingCarList",
          method: "POST",
          data: {
            token: this.data.token
          },
          success: (res) => {
            let arr = []
            let { indexArr } = this.data
            for (let i = 0; i < indexArr.length; i++) {
              arr.push(res.data.data.data[indexArr[i]])
            }
            for (let i = 0; i < arr.length; i++) {
              this.data.ids.push(arr[i].shopping_car_id)
            }
            this.setData({
              goodsList: arr
            })
            this.countAmount()
            this.regAddress()
          }
        })
      }
    })
  },
  //计算选中的商品的总价
  countAmount() {
    let result = this.data.goodsList.reduce((pre, next) => {
      return pre + next.price * next.num
    }, 0)
    if (result == 0) {
      this.setData({
        amount: result
      })
    } else {
      this.setData({
        amount: result.toFixed(2)
      })
    }
  },
  //去支付
  gopay() {
    const {isAddress} = this.data
    if(!isAddress){
      wx.showToast({
        title: '请填写商品地址',
        icon:"none",
        duration:1000
      })
      return
    }
    wx.request({
      url: "http://api_devs.wanxikeji.cn/api/generateOrder",
      method: "POST",
      data: {
        token: this.data.token,
        address_id: this.data.address_id,
        money: this.data.amount,
        shopping_car_ids: this.data.ids
      },
      success: (res) => {
        console.log(res)
        let result = res.data.data
        // this.appid = result.appid
        this.timeStamp = result.timeStamp
        this.nonce_str = result.nonce_str
        this.package = `prepay_id=${result.prepay_id}`
        this.paySign = result.paySign
        // let result = res.data
        wx.requestPayment({
          timeStamp: this.timeStamp,
          nonceStr: this.nonce_str,
          package: this.package,
          signType: 'MD5',
          paySign: this.paySign,
          success:()=>{
            // console.log(res)
            // setTimeout(()=>{
            wx.reLaunch({ url: '/pages/shopingcar/shopingcar?state=1' })
            // },1000)
          },
          fail:()=>{
            // let {indexArr,address} = this.data
            // console.log("选中商品下标的数组",indexArr)
            // console.log("地址",address)
            wx.redirectTo({
              url: `/pages/order/order?id=1`,
            })
          }
        })
      }
    })
  },
  // 地址列表验证（有则展示，无则新增）
  regAddress() {
    wx.request({
      url: 'http://api_devs.wanxikeji.cn/api/userAddressList',
      data: {
        token: this.data.token
      },
      success: res => {
        console.log("用户地址列表为：", res.data)
        //如果地址列表中存在地址 
        if (res.data.data.length) {
          this.setData({
            isAddress: true,
            emptyaddress:false
          })
          //默认的地址
          let temAddress = res.data.data.filter( item => {
            return item.default !== 0
          })
          //如果没有默认地址 那么就让地址列表中第一项设置为地址
          if(temAddress.length==0){
            this.setData({
              address: res.data.data[res.data.data.length-1],
              address_id:res.data.data[res.data.data.length-1].address_id
            })
          }else{
            this.setData({
              address: temAddress[0],
              address_id:temAddress[0].address_id
            })
          }
          wx.getStorage({
            key: 'selectaddress',
            success:(res)=>{
              let newadress = JSON.parse(res.data)
              this.setData({
                address: newadress,
                address_id:newadress.address_id
              })
            }
          })
          console.log("临时地址", temAddress)
          console.log( this.data.address)
        } else {
          //如果没有地址 那么就隐藏地址信息的面板 展示添加地址
          wx.removeStorage({
            key: 'selectaddress',
          })
          this.setData({
            isAddress: false,
            emptyaddress:true
          })
        }
      },
      fail: err => {
        console.log("用户地址获取失败：", err)
      }
    })
  },
  //跳转到添加地址
  jumpToAddAddress() {
    let {emptyaddress} = this.data
    wx.navigateTo({
      url: `../addAddress/addAddress?emptyaddress=${emptyaddress}`,
    })
  },
  //跳转地址列表
  jumpToAddress() {
    wx.removeStorage({
      key: 'selectaddress',
    })
    wx.navigateTo({
      url: '../address/address?hasAddress=true&isOrder=true',
    })
  }
})